package com.itany.book.order.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.OrderDetailResult;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.itany.book.book.service.IBookService;
import com.itany.book.constant.BookStatusConstant;
import com.itany.book.order.dao.OrderMapper;
import com.itany.book.order.service.IRoderService;
import com.itany.book.pojo.*;
import com.itany.book.user.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tyh on 2018/9/23.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderServiceImpl implements IRoderService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderMapper orderMapper;

    // order会调用userService层方法
    @Reference
    private IUserService userService;

    // order会调用bookService层方法
    @Reference
    private IBookService bookService;

    @Override
    public String getQrCode() {
        String qrCode = "";
        try {
            String no = System.currentTimeMillis()+"";
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(no);
            model.setTotalAmount("0.01");
            model.setSubject("天下画集");
            //支付成功后，会进入的地址
            // 下面的地址为ngrok的反向代理地址!
            request.setNotifyUrl("http://yaozhiyuan.free.idcfengye.com/order/order/paySuccess");
            request.setBizModel(model);
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("-------调用成功-------"+response.getBody());
            }else{
                System.out.println("-------调用失败-------"+response.getBody());
            }
            qrCode = response.getQrCode();

        }catch (Exception e){
            e.printStackTrace();
        }
        return qrCode;
    }

    // @Override
    // public String getQrCode() {
    //     String qrCode = "";
    //     return qrCode;
    // }

    @Override
    public Order findOrderDetails(Integer id) {
        Order order = orderMapper.selectOrderDetailsById(id);
        return order;
    }

    /**
     * @param addressId
     * @param cars 书籍id为key， 书籍num为value
     * @param username
     * @return
     */
    @Override
    public String submitOrder(Integer addressId, Map cars, String username) {
        // 1. 根据Username查询userid
        User user = userService.selectByUsername(username);
        Integer userid = user.getId();
        System.out.println("查询到的Userid:"+ userid);

        // 2. for循环根据cars查询bookid查询查询price，乘以num， 算出总价
        // 每本书对应的购买总价
        Double totalPrice = 0.0;
        Map<Integer, Double> bookPrice = new HashMap<>();
        for (Object obj:cars.keySet()){
            Integer bookid = Integer.parseInt(String.valueOf(obj));
            System.out.println("购买的bookid:"+bookid);
            Book book = bookService.findById(bookid);
            Double price = book.getPrice();
            Integer number = Integer.parseInt((String) cars.get(obj));
            Double subTotal = price*number;
            bookPrice.put(bookid,subTotal);
            totalPrice += subTotal;
        }

        // 3. 生成no, alipayno, 插入t_order: userid, addressid, price, flag= false;
        // String no = "yyyyyyyyyyyy123";
        String no = System.currentTimeMillis()+"";
        String alipayno = no;
        Integer flag = BookStatusConstant.NO_PAY;// -1表示未支付
        Order order = new Order();
        order.setNo(no);
        order.setAlipayno(alipayno);
        order.setUserid(userid);
        order.setAddressid(addressId);
        order.setPrice(totalPrice);
        order.setFlag(flag);
        // 返回生成id
        orderMapper.insertOrder(order);
        Integer orderId = order.getId();
        System.out.println("查询到的orderId:"+orderId);
        // 4. for循环： 插入t_order_book: price
        for (Object obj:cars.keySet()){
            Integer bookid = Integer.parseInt(String.valueOf(obj));
            OrderBook ob = new OrderBook();
            ob.setBookid(bookid);
            ob.setOrderid(orderId);
            Integer number = Integer.parseInt((String) cars.get(obj));
            ob.setNum(number);
            Double subPrice = bookPrice.get(bookid);
            ob.setPrice(subPrice);
            orderMapper.insertOrderBook(ob);
        }
        //
        return no;
    }

    // 事务由问题！
    @Override
    public void paySuccess(String no) {
        // 1. 修改t_order状态
        orderMapper.updateOrderFlagTo1(no);
        Integer orderId = orderMapper.selectByno(no);
        System.out.println("订单号id是"+orderId);
        // 2. 修改book数量
        List<OrderBook> orderBooks = (List<OrderBook>) orderMapper.selectOrderBookByOrderId(orderId);

        for (OrderBook orderBook:orderBooks){
            // 需要购买的数量
            Integer total = orderBook.getNum();
            orderMapper.updateBookNumber(orderBook);
            // 3. 依次增加t_book_supplier的sellnum：
            // 每次从BookSupplier选择一个，要求有number>sellNum
            while (total>0){
                BookSupplier bs = orderMapper.selectBookSupplierByBookIdLimit1EnoughNumber(orderBook.getBookid());
                // 现有的余额
                Integer balance = bs.getNumber() - bs.getSellnum();
                if (balance >= total){
                    bs.setSellnum(bs.getSellnum()+total);
                    // 更新bookSupplier的number为当前更新的number
                    orderMapper.updateBookSupplier(bs);
                    break;
                }
                bs.setSellnum(bs.getNumber());
                total -= balance;
            }
        }
    }

    public static void main(String[] args) {
        // OrderServiceImpl orderService = new OrderServiceImpl();
        // Order order= orderService.findOrderDetails(1);
        // System.out.println(order);
        Object o = 1;
        Integer i =(Integer)(o);
        Integer bookid = Integer.parseInt(String.valueOf(o));
        System.out.println(bookid);
    }

}